package com.haiheng.module_main.mode

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.get
import com.haiheng.library_base.http.patch
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.utils.GsonUtil
import com.haiheng.module_main.bean.BookDeliveryOrderStatus
import com.haiheng.module_main.bean.res.bookcar.BookCarBookInfoRes
import com.haiheng.module_main.bean.res.bookcar.BookCarBookResult
import com.haiheng.module_main.bean.res.bookcar.BookDeliveryOrderBean
import com.haiheng.module_main.bean.res.bookcar.BookDeliveryOrderRes
import com.haiheng.module_main.bean.res.bookcar.OrderLocationRes
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2024/8/28 0028
 * @Version: 1.0
 */
class BookDeliveryOrderViewModel:BaseViewModel() {
    var _bookInfoList = MutableLiveData<List<BookDeliveryOrderBean>>(emptyList())
    var _faiMsg = MutableLiveData<String>()

    val bookInfoList: LiveData<List<BookDeliveryOrderBean>> = _bookInfoList
    val faiMsg: LiveData<String> = _faiMsg
    fun getOrderList() {
        viewModelScope.launch {
            try {
//                val request = HttpRequest(API.BOOK_CAR_PATH.GET_ORDER_LIST)
//                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
//                    .putQuery("Page","1")
//                    .putQuery("Count","99")
//                    .putQueryParams("StudyDeskDeliverBookOrderStatus", listOf("1","2"))
//                    .putQuery("IsDeleted",false.toString())

                val request = HttpRequest(API.BOOK_CAR_PATH.GET_ORDER_LIST)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .putQuery("Page", "1") // 传递当前页码
                    .putQuery("PageSize", "99") // 每页10条
                    .putQuery("BookDeliveryOrderStatus", "0")// 状态筛选条件

                var response = get<BookDeliveryOrderRes>(request) {}
                if (response.errorCode == "0"){
                    response.result.items.forEach { bookDeliveryOrderBean ->
                        var list = ArrayList<String>()
                        bookDeliveryOrderBean.items.forEach {bookDeliveryOrderBeanItem ->
                            LogUtils.d("查询 bibliographyId :${bookDeliveryOrderBeanItem.bibliographyId}")
                            val orderRequest = HttpRequest(API.BOOK_CAR_PATH.QUAARY_LOCATION)
                                .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                                .putPath("bibliographyId", bookDeliveryOrderBeanItem.bibliographyId.toString())
                            var orderRes = get<OrderLocationRes>(orderRequest) {}
                            LogUtils.d("查询地址结果：${orderRes}")
                            if (orderRes.errorCode.equals("0")
                                && orderRes.result != null
                                && orderRes.result.isNotEmpty()){
                                orderRes.result.forEach {
                                    LogUtils.d("添加地址：${it.currentBookShelfLayerName}")
                                    if (!it.currentBookShelfLayerName.isNullOrEmpty()){
                                        list.add(it.currentBookShelfLayerName)
                                    }


                                }
                            }
                        }
                        bookDeliveryOrderBean.loaction = list
                    }

                    _bookInfoList.postValue(response.result.items)
                }else{
                    _faiMsg.postValue(response.message)
                    _bookInfoList.postValue(emptyList())
                    LogWriter.d("获取订单异常：${GsonUtil.getString(response)}")
                }

            } catch (ex: Exception) {
                _faiMsg.postValue("${ex}")
                _bookInfoList.postValue(emptyList())
                LogWriter.d("获取订单异常：${ex.message}")
            }
        }

    }



    fun changeStaus(orderId:String,status:String,reson:String? = "",selectReasonS:String?=""){
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.BOOK_CAR_PATH.CHANGE_ORDER_STATUS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .putParam("studyDeskDeliverBookOrderStatus",status)
                    .putParam("administratorNote",reson?:"")
                    .putParam("administratorCancelReason",reson?:"")
                    .putParam("description",if (status.equals("3")) "已送达" else "无法送达")
                    .putPath("studyDeskDeliverBookOrderId",orderId)
                var response = patch<HttpResponse>(request) {}
                if (response.errorCode.equals("0")){
                    _faiMsg.postValue(response.message)
                    getOrderList()
                }else{
                    _faiMsg.postValue("${response.message}")
                }
            }catch (ex:Exception){
                _faiMsg.postValue("${ex}")
                LogWriter.d("查询书车异常：${ex.message}")
            }
        }
    }

    fun changeOrderStatus(orderStatus: BookDeliveryOrderStatus, orderNumber: String,reson:String? = ""){
        viewModelScope.launch {
            try {
                var isNeedDeleteLocal = false
                var  url = ""
                when(orderStatus){
                    BookDeliveryOrderStatus.PREPARING->{
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_PREPARATION
                    }
                    BookDeliveryOrderStatus.DELIVERING->{
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_DELIVERIES
                    }
                    BookDeliveryOrderStatus.CANCELLED->{
                        isNeedDeleteLocal =true
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_CANCEL
                    }
                    BookDeliveryOrderStatus.AWAITING_PICKUP->{
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_ARRIVALS
                    }
                    BookDeliveryOrderStatus.COMPLETED->{
                        isNeedDeleteLocal=true
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_COMPLETIONS
                    }
                    BookDeliveryOrderStatus.PICKUP_EXPIRED->{
                        isNeedDeleteLocal=true
                        url = API.BOOK_CAR_PATH.CHANGE_DELIVERY_ORDERS_CANCEL
                    }
                }
                var jsonParams = mutableMapOf<String,String>()
                jsonParams.put("message","${reson}")
//                jsonParams.put("machineUuid", ConfigManager.getConfigItem(ConfigIdEnum.MAC_ADDRESS).editTextContent)
                val request = HttpRequest(url)
//                    .putHeader(Domain.KEY_NAME, Domain.VALUE_DELIVERY_BOOK_API)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .putPath("orderNumber",orderNumber)
                    .setJsonObjec(jsonParams)
                var response  = postJson<HttpResponse>(request)
                LogWriter.d("修改订单${orderNumber}  状态结果：${response.toJson()}")
                if (response.errorCode == "0"){
                    _faiMsg.postValue(response.message)
                    getOrderList()
                }else{
                    _faiMsg.postValue("${response.message}")
                }
            }catch (ex:Exception){
                _faiMsg.postValue("${ex}")
                LogWriter.d("改变订单状态异常：${ex}")
            }
        }
    }

}